use std::time::Duration;

use axum::{
    Json, Router, middleware,
    response::IntoResponse,
    routing::{get, post},
};
use rust_embed::Embed;

#[allow(unused_imports)]
use tower_http::services::{ServeDir, ServeFile};

use crate::{model::User, service::auth};
#[derive(Embed)]
#[folder = "../server-front/dist"]
struct Asset;

#[allow(dead_code)]
async fn static_embed(uri: axum::http::Uri) -> impl IntoResponse {
    let path = uri.path().trim_start_matches('/');
    match Asset::get(path) {
        Some(content) => {
            let mime = mime_guess::from_path(path).first_or_octet_stream();
            (
                axum::http::StatusCode::OK,
                [(axum::http::header::CONTENT_TYPE, mime.as_ref())],
                content.data,
            )
                .into_response()
        }
        None => match Asset::get("index.html") {
            Some(content) => (
                axum::http::StatusCode::OK,
                [(axum::http::header::CONTENT_TYPE, "text/html")],
                content.data,
            )
                .into_response(),
            None => (axum::http::StatusCode::NOT_FOUND, "404 Not Found").into_response(),
        },
    }
}
pub fn route() -> Router {
    let api = Router::new().nest(
        "/user",
        Router::new()
            .route(
                "/",
                get(|| async {
                    let user = User {
                        id: 1,
                        name: "lulu".to_string(),
                        email: Some("lulu@qq.com".to_string()),
                    };
                    tokio::time::sleep(Duration::from_secs(3)).await;
                    Json(user)
                }),
            )
            .route(
                "/",
                post(|Json(user): Json<User>| async move { println!("user: {:?}", user) }),
            )
            .route(
                "/list",
                get(|| async {
                    let users = vec![User {
                        id: 1,
                        name: "lulu".to_string(),
                        email: Some("lulu@qq.com".to_string()),
                    }];
                    return Json(users);
                }),
            ),
    );

    // let static_root = ServeDir::new("../server-front/dist")
    //     .fallback(ServeFile::new("../server-front/dist/index.html"));

    Router::new()
        .nest("/api", api)
        .layer(middleware::from_fn(auth))
        .fallback(static_embed)
    // .fallback_service(static_root)
}
